package com.guan.core;

import com.guan.core.util.ClassScanner;
import com.guan.core.util.Contants;
import com.guan.jdbc.db.DBUtil;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.Map;

/**
 * 监听应用的上下文
 * Created by Administrator on 2018/1/15 0015.
 */
public class ApplicationListener implements ServletContextListener{
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        //应用程序加载的时候
        String basePackage = (String) servletContextEvent.getServletContext().getInitParameter(Contants.PACKAGE_NAME);
        //扫描加载所有类
        Map<String,Class<?>> result = ClassScanner.scannerClass(basePackage);
        //初始化bean容器
        BeanContext b = new BeanContext(result);
        //将bean容器放在整个上下文中
        servletContextEvent.getServletContext().setAttribute(Contants.CONTEXT_NAME,b);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        //应用程序卸载的时候 释放数据库连接池
        DBUtil.release();
    }
}
